package com.lqk.channel.filechannel;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChannel读操作
 */
public class FileChannelDemo1 {
    /*
    FileChannel 读取数据到buffe中
     */
    public static void main(String[] args) throws Exception {
        //创建 FileChannel
        RandomAccessFile accessFile=new RandomAccessFile("F:\\lqk\\01.txt","rw");
        FileChannel channel = accessFile.getChannel();
        //创建 Buffer 缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);

        //读取数据到 buffer 中
        int bytesRead = channel.read(buf);

        while (bytesRead != -1){
            System.out.println("读取了："+bytesRead);
            buf.flip(); //读写模式的转换
            while (buf.hasRemaining()){ // buf.hasRemaining(): buf 中是否有剩余的数据
                System.out.println((char) buf.get());
            }
            buf.clear();
            bytesRead=channel.read(buf);    //将剩余的数据读到 buffer 中
        }
        accessFile.close();
        System.out.println("操作结束！");
    }
}
